import Taro from "@tarojs/taro";
import React, { useEffect } from "react";
import { View, Text, Canvas } from "@tarojs/components";
import F2 from "@antv/f2";
import "./index.scss";

export default () => {
  const initChart = (config) => {
    // F2 对数据源格式的要求，仅仅是 JSON 数组，数组的每个元素是一个标准 JSON 对象。
    const data = [
      { genre: "Sports", sold: 275 },
      { genre: "Strategy", sold: 115 },
      { genre: "Action", sold: 120 },
      { genre: "Shooter", sold: 350 },
      { genre: "Other", sold: 150 },
    ];

    const chart = new F2.Chart(
      Object.assign(config, {
        appendPadding: [10, 15, 10, 15],
        // 预留展示tooltip高度
        padding: [40, "auto", "auto"],
      })
    );

    // Step 2: 载入数据源
    chart.source(data);

    // Step 3：创建图形语法，绘制柱状图，由 genre 和 sold 两个属性决定图形位置，genre 映射至 x 轴，sold 映射至 y 轴
    chart.interval().position("genre*sold").color("genre");

    // Step 4: 渲染图表
    chart.render();
  };
  const onWxCanvas = () => {
    const query = Taro.createSelectorQuery();
    query
      .select("#" + "chart-id")
      .fields({
        node: true,
        size: true,
      })
      .exec((res) => {
        const { node, width, height } = res[0];
        const context = node.getContext("2d");
        const pixelRatio = Taro.getSystemInfoSync().pixelRatio;
        // 高清设置
        node.width = width * pixelRatio;
        node.height = height * pixelRatio;
        //  chart全局设置
        const appendPadding = 5;
        const config = { context, width, height, pixelRatio, appendPadding };
        const chart = initChart(config);
        if (chart) {
          //   this.chart = chart;
          //   this.canvasEl = chart.get("el");
        }
      });
  };

  useEffect(() => {
    setTimeout(() => {
      onWxCanvas();
    }, 500);
  }, []);
  return (
    <>
      <View>
        <Canvas style="width: 300px; height: 200px;" type="2d" id="chart-id" />
      </View>
    </>
  );
};
